package net.freebytes.websocket.core.controller;

import net.freebytes.websocket.core.service.WebSocketService;
import net.freebytes.websocket.common.dto.WsMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * websocket对外接口
 *
 * @author 千里明月
 * @date 2021/8/8
 **/
@RestController
@RequestMapping("/api/freebytes/ws")
public class WebSocketController {

    @Autowired
    private WebSocketService webSocketService;

    /**
     * 推送websocket消息给所有用户
     *
     * @param prefix 客户端订阅地址的前缀信息
     * @param item   客户端订阅地址的补充信息
     * @param obj
     * @throws Exception
     */
    @PostMapping("sent-to-all")
    public void sentToAllUsers(String prefix, String item, @RequestBody Object obj) throws Exception {
        webSocketService.sendToAll(prefix, item, obj);
    }

    /**
     * 指定用户推送websocket消息
     *
     * @param prefix
     * @param item
     * @param msg
     * @throws Exception
     */
    @PostMapping("sent-to-user")
    public void sentToUsers(String prefix, String item, @RequestBody WsMessage msg) throws Exception {
        webSocketService.sentToUsers(prefix, item, msg);
    }
}
